

task default: [
  :eval_erb, 
  :make_binaries_executable,
  :copy_readme_file_to_root
]

task :eval_erb do

  # Evaluate the ERB markup in all files (expect Rakefile)
  # in the context of the (fake) gem specification object.
  PARAMS[:gemspec].instance_exec do
    require 'fileutils'
    require 'pathname'
    require 'erb'

    Dir['**/*'].reject{|fn|
      fn == 'Rakefile' or fn.pathmap('%x') == '.gemspec'
    }.each do |_filename|

      # Skip directories
      _file = Pathname.new _filename
      next unless _file.file?

      # Resolve markup
      _text = _file.read
      _text = ERB.new(_text).result binding

      # Write resolved file
      _outdir = "#{PARAMS[:next_step_dir]}/#{_filename.pathmap '%d'}"
      FileUtils.mkdir_p _outdir
      _outfile = Pathname (
        "#{_outdir}/#{_filename.pathmap '%f'}"
      )
      _outfile.write _text
    end
  end

end

task :make_binaries_executable do
  Dir["#{PARAMS[:next_step_dir]}/bin/*"].each do |filename|
    chmod 'a+x', filename
  end
end

task :copy_readme_file_to_root do
  Dir["#{PARAMS[:next_step_dir]}/README*"].each do |filename|

    # Copy
    cp filename, '..'
  end
end



# Task parameters ##################################
PARAMS = {
  next_step_dir: Dir['../2.*'].first,
  gemspec:       nil
}

# Capture the gem specification by 'evaluating the *.gemspec file
# using a fake OpenStruct object that passes for a
# Gem::Specification instance.
begin
  require 'ostruct'
  require 'pathname'

  module Gem
    # Fake Gem::Specification class
    class Specification
      def initialize 
        @spec = OpenStruct.new
        @spec.executables = []
        @spec.metadata = {}
        @spec.development_dependencies = []
        @spec.singleton_class.class_eval do
          def add_development_dependency *geminfo
            self.development_dependencies << geminfo
          end
        end

        yield @spec
        ::PARAMS[:gemspec] = @spec
      end
    end
  end
  
  def read_gemspec
    gemspec = Dir['../*/*.gemspec'].first
    return unless gemspec
    gemspec = Pathname.new(gemspec)
    return unless gemspec.file?
    gemspec = gemspec.read
    self.instance_eval gemspec
  end

  read_gemspec
end

